package com.patchmanage.back.aop;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.patchmanage.back.annotation.OperLog;
import com.patchmanage.back.config.Constants;
import com.patchmanage.back.entity.Admin;
import com.patchmanage.back.mongodb.model.SystemLog;
import com.patchmanage.back.redis.JedisTemplate;
import com.patchmanage.back.service.IAdminService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 切面处理类，操作日志异常日志记录处理
 */
@Aspect
@Component
public class OperLogAspect {

    @Autowired
    private JedisTemplate<String> jedisTemplate;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.patchmanage.back.annotation.OperLog)")
    public void operLogPoinCut() {
    }

    /*
    *//**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     *//*
    @Pointcut("execution(* com.hyd.zcar.cms.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }*/

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     */
    @Before("operLogPoinCut()")
    public void saveOperLog(JoinPoint joinPoint) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            SystemLog systemLog = new SystemLog();
            // 获取操作
            OperLog operLogAnnotation = method.getAnnotation(OperLog.class);
            if (operLogAnnotation != null) {
                String operModul = operLogAnnotation.operModul();
                String operDesc = operLogAnnotation.operDesc();
                systemLog.setOperModul(operModul); // 操作模块
                systemLog.setContent(operDesc); //操作描述
            }
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;

            systemLog.setMethod(methodName); // 请求方法

            // 请求的参数
            String token = request.getHeader("token");
            String tokenFromRedis = jedisTemplate.get(Constants.userToken + token);
            Admin admin = null;
            if(StrUtil.isNotBlank(tokenFromRedis)){
                admin = adminService.getById(Integer.valueOf(tokenFromRedis));
            }
            // 将参数所在的数组转换成json
            String params = JSONUtil.toJsonStr(joinPoint.getArgs());

            //params = "{\"strategyName\":\"测试1\",\"riskLevel\":1,\"rollbackSwitch\":0,\"patchDistributeType\":1,\"effectiveTime\":\"22:09~22:09\",\"systemRestartSwitch\":0,\"type\":1,\"executionTime\":\"{\\\"date\\\":\\\"2021-07-06T12:22:33.267Z\\\",\\\"mode\\\":1,\\\"time\\\":\\\"2021-07-06 2021-07-06 22:08:00\\\"}\",\"priorityLevel\":0,\"id\":8,\"patchGroupId\":1}";
           // params = StringEscapeUtils.unescapeJava(params);
            params = params.replace("[","");
            params = params.replace("]","");

            JSONObject jsonObject = JSONUtil.parseObj(params);
            String operUserName = "";
            String operUserId = "";

            if(request.getRequestURI().contains("login")){
                jsonObject.set("password","******");
                operUserName = jsonObject.getStr("username");

            }else{
                operUserName = admin!=null?admin.getUsername().toString():null;
                operUserId = admin!=null?admin.getId().toString():null;
            }

            systemLog.setOperUserName(operUserName);
            systemLog.setOperUserId(operUserId);

            systemLog.setOperRequParam(jsonObject.toString()); // 请求参数
            systemLog.setOperUri(request.getRequestURI()); // 请求URI
            systemLog.setCreateTime(LocalDateTime.now());
            mongoTemplate.insert(systemLog , "system_log");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     *//*
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        ExceptionLog excepLog = new ExceptionLog();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            excepLog.setExcId(UuidUtil.get32UUID());
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            excepLog.setExcRequParam(params); // 请求参数
            excepLog.setOperMethod(methodName); // 请求方法名
            excepLog.setExcName(e.getClass().getName()); // 异常名称
            excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
            excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
            excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
            excepLog.setOperUri(request.getRequestURI()); // 操作URI
            excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作员IP
            excepLog.setOperVer(operVer); // 操作版本号
            excepLog.setOperCreateTime(new Date()); // 发生异常时间

            exceptionLogService.insert(excepLog);

        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }*/

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }


}